//
//  CurveViewController.m
//  RealTimeCurve
//
//  Created by wu xiaoming on 13-1-24.
//  Copyright (c) 2013年 wu xiaoming. All rights reserved.
//

#import "CurveViewController.h"

#import "PublicMethodEngine.h"

@interface CurveViewController ()

@end

@implementation CurveViewController
@synthesize closeBtn;
@synthesize webViewForSelectDate;
@synthesize timer;

static ASIHTTPConnection *getData_connect;


- (id)initWithDataType:(int)type{
    
    self = [super init];
    if (self) {
        dataType = type;
    }
    return self;
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)viewDidLoad
{

    //test
     //[self dataDone];
    
    [self loadData]
    ;
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}
-(void)closePage
{
    UINavigationController* naviController = (UINavigationController*)[[UIApplication sharedApplication] keyWindow].rootViewController;
    [naviController popViewControllerAnimated:YES];
}
-(void)updateData
{
    //取得当前时间，x轴
    NSDate* nowDate = [[NSDate alloc]init];
    NSTimeInterval nowTimeInterval = [nowDate timeIntervalSince1970] * 500;
    [nowDate release];
    
    //随机温度，y轴
    int temperature = [self getRandomNumber:20 to:50];
    
    NSMutableString* jsStr = [[NSMutableString alloc] initWithCapacity:0];
    [jsStr appendFormat:@"updateData(%f,%d)",nowTimeInterval,temperature];
    
       
    [webViewForSelectDate stringByEvaluatingJavaScriptFromString:jsStr];
}
//获取一个随机整数，范围在[from,to），包括from，不包括to
-(int)getRandomNumber:(int)from to:(int)to
{
    return (int)(from  + (arc4random() % (to - from + 1)));
}
#pragma mark - delegate of webview
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    return YES;
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
   
    if (dataType == 1) {
        
        for (int i = 0; i <= dataArray.count -1; i++) {
            
            NSDictionary *dict = [dataArray objectAtIndex:i];
            
            NSString *DataUploadTime = [dict objectForKey:@"DataUploadTime"];
                       
            //取得当前时间，x轴
            NSDate * nowDate = [[PublicMethodEngine sharedPublicMethodEngine] NSStringDateToNSDate:DataUploadTime];
            NSTimeInterval nowTimeInterval = [nowDate timeIntervalSince1970]*1000;
           // [nowDate release];
            
            
            //y轴
            float weight = 50;
            
            if (![[dict objectForKey:@"Weight"] isMemberOfClass:[NSNull class]]) {
                weight = [[dict objectForKey:@"Weight"] floatValue];
            }
                                   
            NSMutableString* jsStr = [[NSMutableString alloc] initWithCapacity:0];
            
            int islast = 0;
            
            if (i == dataArray.count - 1) {
                islast = 1;
            }
            
            long long int datetime = (long long int)nowTimeInterval;
            
            [jsStr appendFormat:@"updateData(%lld,%f,%d)",datetime,weight,islast];
            
            
            [webViewForSelectDate stringByEvaluatingJavaScriptFromString:jsStr];
        }
        
    }


    
    if (dataType == 2) {
        
        for (int i = 0; i <= dataArray.count -1; i++) {
            
            NSDictionary *dict = [dataArray objectAtIndex:i];
            
            NSString *DataUploadTime = [dict objectForKey:@"DataUploadTime"];
            
            //取得当前时间，x轴
            NSDate * nowDate = [[PublicMethodEngine sharedPublicMethodEngine] NSStringDateToNSDate:DataUploadTime];
            NSTimeInterval nowTimeInterval = [nowDate timeIntervalSince1970]*1000;
            // [nowDate release];
            
            
            //y轴
            float UriaProtein = 40;
            
            if (![[dict objectForKey:@"UriaProtein"] isMemberOfClass:[NSNull class]]) {
                UriaProtein = [[dict objectForKey:@"UriaProtein"] floatValue];
            }
            
            NSMutableString* jsStr = [[NSMutableString alloc] initWithCapacity:0];
            
            int islast = 0;
            
            if (i == dataArray.count - 1) {
                islast = 1;
            }
            
            long long int datetime = (long long int)nowTimeInterval;
            
            [jsStr appendFormat:@"updateData(%lld,%f,%d)",datetime,UriaProtein,islast];
            
            
            [webViewForSelectDate stringByEvaluatingJavaScriptFromString:jsStr];
        }
        
    }
    
    
    if (dataType == 3) {
        
        for (int i = 0; i <= dataArray.count -1; i++) {
            
            NSDictionary *dict = [dataArray objectAtIndex:i];
            
            NSString *DataUploadTime = [dict objectForKey:@"DataUploadTime"];
            
            //取得当前时间，x轴
            NSDate * nowDate = [[PublicMethodEngine sharedPublicMethodEngine] NSStringDateToNSDate:DataUploadTime];
            NSTimeInterval nowTimeInterval = [nowDate timeIntervalSince1970]*1000;
            // [nowDate release];
            
            
            //y轴
            float BloodSugar = 100;
            
            if (![[dict objectForKey:@"BloodSugar"] isMemberOfClass:[NSNull class]]) {
                BloodSugar = [[dict objectForKey:@"BloodSugar"] floatValue];
            }
            
            NSMutableString* jsStr = [[NSMutableString alloc] initWithCapacity:0];
            
            int islast = 0;
            
            if (i == dataArray.count - 1) {
                islast = 1;
            }
            
            long long int datetime = (long long int)nowTimeInterval;
            
            [jsStr appendFormat:@"updateData(%lld,%f,%d)",datetime,BloodSugar,islast];
            
            
            [webViewForSelectDate stringByEvaluatingJavaScriptFromString:jsStr];
        }
        
    }
    
    
    if (dataType == 5) {
        
        for (int i = 1; i <= 1200; i++) {
            //取得当前时间，x轴
            NSDate* nowDate = [[NSDate alloc]init];
            NSTimeInterval nowTimeInterval = [nowDate timeIntervalSince1970]*1000 + i*500;
            [nowDate release];
            
            //随机温度，y轴
            int temperature = [self getRandomNumber:120 to:180];
            long long int datetime = (long long int)nowTimeInterval;
            
            NSMutableString* jsStr = [[NSMutableString alloc] initWithCapacity:0];
            [jsStr appendFormat:@"updateData(%lld,%d,%d)",datetime,temperature,i];
            
            
            [webViewForSelectDate stringByEvaluatingJavaScriptFromString:jsStr];
        }

    }
    
      
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return UIDeviceOrientationIsLandscape(interfaceOrientation);
}
#ifdef __IPHONE_6_0
-(BOOL)shouldAutorotate
{
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    return UIDeviceOrientationIsLandscape(orientation);
}

-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}
#endif
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadData{
    
    NSString *uid = [[NSUserDefaults standardUserDefaults] valueForKey:USER_ID];
    
    NSString *urlString = nil;
    
    switch (dataType) {
        case 1:
            urlString = [NSString stringWithFormat:@"%@/MobileHealth/WeightAction.aspx?UserID=%@",BASEURL,uid];
            break;
        case 2:
            urlString = [NSString stringWithFormat:@"%@/MobileHealth/UriaProteinAction.aspx?UserID=%@",BASEURL,uid];
            break;
        case 3:
            urlString = [NSString stringWithFormat:@"%@/MobileHealth/BloodSugarAction.aspx?UserID=%@",BASEURL,uid];
            break;
        case 4:
            urlString = [NSString stringWithFormat:@"%@/MobileHealth/BloodPressureAction.aspx?UserID=%@",BASEURL,uid];
            break;
        case 5:
            urlString = [NSString stringWithFormat:@"%@/MobileHealth/HeartAction.aspx?UserID=%@",BASEURL,uid];
            break;
        default:
            break;
    }
    
    
    
    
    
    
	NSURL *url = [NSURL URLWithString:urlString];
    
    
    if (getData_connect != nil) {
        getData_connect.connectionDelegate = nil;
        [getData_connect release];
        getData_connect = nil;
    }
    
    getData_connect = [[ASIHTTPConnection alloc] initGETWithURL:url resultDict:YES isCache:YES];
    getData_connect.connectionDelegate = self;
    
    [getData_connect startAsynchronous];
    
    
    [LoadingView showDefaultLoadingView];
}


#pragma mark connection delegate
- (void)requestFinished:(ASIHTTPConnection *)connection resultDict:(NSDictionary *)dict URL:(NSURL *)url info:(NSDictionary *)info{
    [LoadingView hideWithAnimated:YES];
    
    CLog(@"data = %@",dict);
    if (dict) {
        NSArray *array = [dict objectForKey:@"datalist"];
        if (array != nil && array.count > 0) {
            
            if (dataArray == nil) {
                dataArray = [[NSMutableArray alloc]init];
            }
            else{
                [dataArray removeAllObjects];
            }
            [dataArray addObjectsFromArray:array];
            [self dataDone];
        }
    }
    
}

- (void)requestFailed:(ASIHTTPConnection *)connection error:(NSError *)error URL:(NSURL *)url info:(NSDictionary *)info{
    [LoadingView hideWithAnimated:YES];
    
}

- (void)dataDone{
   
   
    
    //所有的资源都在source.bundle这个文件夹里
    NSString* htmlPath ;
    

    
    switch (dataType) {
        case 1:
           //weight
        {
            
            htmlPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"chartsource.bundle/index_weight.html"];
        }
            
            break;
        case 2:
          htmlPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"chartsource.bundle/index_uri.html"];
            break;
        case 3:
           htmlPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"chartsource.bundle/index_blood.html"];
            break;
        case 4:
           htmlPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"chartsource.bundle/index.html"];
            break;
        case 5:
            [LoadingView showDurationMessageLoadingViewWith:30 message:@"正在加载数据"];
            htmlPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"chartsource.bundle/index.html"];
            break;
        default:
            break;
    }

    
    CGRect webFrame = self.view.frame;
    webFrame.origin.x = 0;
    webFrame.origin.y =  0;
    
    webViewForSelectDate = [[UIWebView alloc] initWithFrame:webFrame];
    webViewForSelectDate.delegate = self;
    webViewForSelectDate.scalesPageToFit = YES;
    webViewForSelectDate.opaque = NO;
    webViewForSelectDate.backgroundColor = [UIColor clearColor];
    webViewForSelectDate.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
    [self.view addSubview:webViewForSelectDate];
    
      NSURL* url = [NSURL fileURLWithPath:htmlPath];
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    [webViewForSelectDate loadRequest:request];
    int trueWidth = self.view.frame.size.width;
    if (trueWidth < self.view.frame.size.height && ![UIApplication sharedApplication].statusBarHidden)
    {
        trueWidth = self.view.frame.size.height + MIN([UIApplication sharedApplication].statusBarFrame.size.height,[UIApplication sharedApplication].statusBarFrame.size.width);
    }
    CGRect closeBtnFrame = CGRectMake(trueWidth - 70, 0, 70, 20);
    closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [closeBtn setFrame:closeBtnFrame];
    [closeBtn setTitle:@"close" forState:UIControlStateNormal];
    [closeBtn addTarget:self action:@selector(closePage) forControlEvents:UIControlEventTouchUpInside];
    [closeBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [self.view addSubview:closeBtn];
    [self.view bringSubviewToFront:closeBtn];

    
}

-(void)dealloc
{
    [closeBtn release];
    [webViewForSelectDate release];
    
    if (getData_connect != nil) {
        getData_connect.connectionDelegate = nil;
        [getData_connect release];
        getData_connect = nil;
    }
    
    [dataArray release];

    
    [super dealloc];
}
@end
